<template>
  <div class="login-container">
    <div class="pic-box">
      <img src="@/assets/login_images/login_bg.png" alt="" class="pic" />
    </div>
    <el-form
      ref="formRef"
      class="login-form"
      label-position="left"
      :model="form"
      :rules="rules"
    >
      <img src="@/assets/logo.png" alt="" class="logo" />
      <div class="title">
        欢迎登录
        <br />
        {{ title }}
      </div>
      <!-- <div class="title-tips">
        {{ translateTitle('欢迎来到') }}{{ title }}！
      </div> -->
      <el-form-item prop="username">
        <el-input
          v-model.trim="form.username"
          v-focus
          :placeholder="translateTitle('请输入用户名')"
          tabindex="1"
          type="text"
        >
          <template #prefix>
            <vab-icon icon="user-line" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          :key="passwordType"
          ref="passwordRef"
          v-model.trim="form.password"
          :placeholder="translateTitle('请输入密码')"
          tabindex="2"
          :type="passwordType"
          @keyup.enter="handleLogin"
        >
          <template #prefix>
            <vab-icon icon="lock-line" />
          </template>
          <!-- <template v-if="passwordType === 'password'" #suffix>
            <vab-icon
              class="show-password"
              icon="eye-off-line"
              @click="handlePassword"
            />
          </template>
          <template v-else #suffix>
            <vab-icon
              class="show-password"
              icon="eye-line"
              @click="handlePassword"
            />
          </template> -->
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="login-btn"
          :loading="loading"
          type="primary"
          @click="handleLogin"
        >
          {{ translateTitle('登录') }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <template #default>
          <el-checkbox v-model="form.rememberMe">
            {{ translateTitle('记住密码') }}
          </el-checkbox>
        </template>
      </el-form-item>
      <!-- <el-form-item>
        <router-link to="/register">
          {{ translateTitle('注册') }}
        </router-link>
      </el-form-item> -->
    </el-form>

    <!-- <vab-footer /> -->
    <!-- <Verify
      ref="verify"
      :captcha-type="captchaType"
      :img-size="{ width: '400px', height: '200px' }"
      mode="pop"
      @success="handleLogin"
    /> -->
  </div>
</template>

<script>
  import { useSettingsStore } from '@/store/modules/settings'
  import { useUserStore } from '@/store/modules/user'
  import { translate } from '@/i18n'
  import { isPassword } from '@/utils/validate'
  import { getTenantIdByName } from '@/api/login/index'
  export default defineComponent({
    name: 'Login',
    directives: {
      focus: {
        mounted(el) {
          el.querySelector('input').focus()
        },
      },
    },
    setup() {
      const route = useRoute()
      const router = useRouter()

      const userStore = useUserStore()
      const settingsStore = useSettingsStore()

      const login = (form) => userStore.login(form)
      const tenantId = (form) => userStore.setTenantId(form)
      const validateUsername = (rule, value, callback) => {
        if ('' === value) callback(new Error(translate('用户名不能为空')))
        else callback()
      }
      const validatePassword = (rule, value, callback) => {
        if (!isPassword(value))
          callback(new Error(translate('密码不能少于12位')))
        else callback()
      }

      const state = reactive({
        verify: null,
        formRef: null,
        passwordRef: null,
        captchaType: 'clickWord',
        form: {
          tenantName: '渤海钻探',
          username: 'admin',
          password: 'dbs@Z1b2c3d4',
          captchaVerification: '',
          rememberMe: true,
        },
        rules: {
          username: [
            {
              required: true,
              trigger: 'blur',
              validator: validateUsername,
            },
          ],
          password: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePassword,
            },
          ],
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined,
        timer: 0,
        codeUrl: 'https://www.oschina.net/action/user/captcha',
        previewText: '',
      })

      const handleRoute = () => {
        return state.redirect === '/404' || state.redirect === '/403'
          ? '/'
          : state.redirect
      }
      const handlePassword = () => {
        state.passwordType === 'password'
          ? (state.passwordType = '')
          : (state.passwordType = 'password')
        nextTick(() => {
          state['passwordRef'].focus()
        })
      }
      const handleLogin = async () => {
        state['formRef'].validate(async (valid) => {
          if (valid)
            try {
              state.loading = true
              //读取租户信息
              const { data } = await getTenantIdByName(
                state.form.tenantName,
                {}
              )
              //存取租户信息
              tenantId(data)
              //登记
              await login(state.form).catch(() => {})
              await router.push(handleRoute())
            } finally {
              state.loading = false
            }
        })
      }

      const getTenantId = () => {
        getTenantIdByName(state.form.tenantName, {})
      }

      const changeCode = () => {
        state.codeUrl = `https://www.oschina.net/action/user/captcha?timestamp=${new Date().getTime()}`
      }
      watchEffect(() => {
        state.redirect = (route.query && route.query.redirect) || '/'
      })

      onBeforeRouteLeave((to, from, next) => {
        clearInterval(state.timer)
        next()
      })

      return {
        translateTitle: translate,
        ...toRefs(state),
        title: settingsStore.getTitle,
        handlePassword,
        handleLogin,
        changeCode,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .login-container {
    display: flex;
    height: 100vh;
    background: #fff;
    overflow: hidden;

    .pic-box {
      flex: 1;

      .pic {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .login-form {
      display: flex;
      flex-direction: column;
      justify-content: center;
      width: 520px;
      flex: 0 0 520px;
      padding: 0 60px;
      overflow: hidden;

      .logo {
        width: 57px;
      }

      .title {
        margin-top: 24px;
        margin-bottom: 48px;
        font-size: 32px;
        font-weight: 500;
        line-height: 42px;
        color: $base-color-text-regular;
      }

      .title-tips {
        margin-top: 29px;
        font-size: 26px;
        font-weight: 400;
        color: var(--el-color-white);
      }

      .login-btn {
        width: 100%;
        height: 40px;
        margin-top: 24px;
        font-size: 18px;
        background: var(--el-color-primary);
        border: 0;

        &:hover {
          opacity: 0.9;
        }
      }

      .tips {
        margin-bottom: 10px;
        font-size: $base-font-size-default;
        color: var(--el-color-white);

        span {
          &:first-of-type {
            margin-right: 16px;
          }
        }
      }

      .title-container {
        position: relative;

        .title {
          margin: 0 auto 40px;
          font-size: 34px;
          font-weight: bold;
          color: var(--el-color-primary);
          text-align: center;
        }
      }

      .show-password {
        float: right;
        width: 32px;
        height: 32px;
        font-size: 16px;
      }

      :deep() {
        .el-form-item {
          padding-right: 0;
          margin-bottom: 24px;
          color: #454545;
          background: transparent;
          border: 1px solid transparent;
          border-radius: 2px;
        }

        .el-input {
          box-sizing: border-box;

          input {
            height: 40px;
            line-height: 40px;
            border: 0;
          }
        }

        .code {
          position: absolute;
          top: 4px;
          right: 4px;
          cursor: pointer;
          border-radius: $base-border-radius;
        }
      }
    }
  }
</style>
